package com.example.teamtribe.main.seek;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.model.FileModel;
import com.example.teamtribe.common.model.UserModel;
import com.example.teamtribe.database.User;
import com.example.teamtribe.event.Head;
import com.example.teamtribe.event.SearchUser;
import com.example.teamtribe.utils.Utility;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class SeekPresenter implements SeekContract.Presenter {

    private SeekContract.View view;
    private SeekModel model;

    public SeekPresenter(SeekContract.View view) {
        this.view = view;
        model = new SeekModel();
    }

    @Override
    public void find(String query) {
        findUserByName(query);
        findUserByPhone(query);
        findUserByEmail(query);
    }

    private void findUserByName(String username) {
        model.getUserByName(username, findUserBack());
    }

    private void findUserByPhone(String phone) {
        model.getUserByPhone(phone, findUserBack());
    }

    private void findUserByEmail(String email) {
        model.getUserByEmail(email, findUserBack());
    }

    private Back findUserBack() {
        return new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                List<Integer> ids = bundle.getIntegerArrayList("id");
                for (int i : ids) {
                    UserModel.getInstance().getUser(Utility.getToken(), i, fileBack());
                }
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
            }
        };
    }

    private FileModel.FileBack fileBack() {
        return new FileModel.FileBack() {
            @Override
            public void loadSuccess(String fileName) {
                EventBus.getDefault().post(new Head());
            }

            @Override
            public void success(@Nullable Bundle bundle) {
                User user = bundle.getParcelable("user");
                user.saveOrUpdate();
                EventBus.getDefault().post(new SearchUser(user));
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
            }
        };
    }
}
